package org.lemon.transport.coap.adapter;

import com.google.gson.JsonParser;
import com.google.protobuf.Descriptors;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.coap.Response;
import org.lemon.transport.context.adaptor.AdaptorException;
import org.lemon.transport.context.adaptor.JsonConverter;
import org.lemon.transport.context.adaptor.ProtoConverter;
import org.server.transport.gen.TransportProto;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@Component
public class ProtoCoapAdaptor implements CoapTransportAdaptor {

    @Override
    public TransportProto.PostTelemetryMsg convertToPostTelemetry(UUID sessionId, Request inbound, Descriptors.Descriptor telemetryMsgDescriptor) throws AdaptorException {
        ProtoConverter.validateDescriptor(telemetryMsgDescriptor);
        try {
            return JsonConverter.convertToTelemetryProto(new JsonParser().parse(ProtoConverter.dynamicMsgToJson(inbound.getPayload(), telemetryMsgDescriptor)));
        } catch (Exception e) {
            throw new AdaptorException(e);
        }
    }

    @Override
    public TransportProto.PostAttributeMsg convertToPostAttributes(UUID sessionId, Request inbound, Descriptors.Descriptor attributesMsgDescriptor) throws AdaptorException {
        ProtoConverter.validateDescriptor(attributesMsgDescriptor);
        try {
            return JsonConverter.convertToAttributesProto(new JsonParser().parse(ProtoConverter.dynamicMsgToJson(inbound.getPayload(), attributesMsgDescriptor)));
        } catch (Exception e) {
            throw new AdaptorException(e);
        }
    }

    @Override
    public TransportProto.GetAttributeRequestMsg convertToGetAttributes(UUID sessionId, Request inbound) throws AdaptorException {
        return null;
    }

    @Override
    public Response convertToPublish(TransportProto.AttributeUpdateNotificationMsg msg) throws AdaptorException {
        return null;
    }

    @Override
    public Response convertToPublish(TransportProto.GetAttributeResponseMsg msg) throws AdaptorException {
        return null;
    }

    @Override
    public int getContentFormat() {
        return MediaTypeRegistry.APPLICATION_OCTET_STREAM;
    }
}
